package com.shiguiwu.springmybatis.spring.aop.demo;


import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.aop.Pointcut;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.support.DefaultPointcutAdvisor;

import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @description: 方法的耗时统计
 * @author: stone
 * @date: Created by 2021/5/19 14:50
 * @version: 1.0.0
 * @pakeage: com.shiguiwu.springmybatis.spring.aop.demo
 */
public class DemoV2Tests {

    public static void main(String[] args) {

        UserService target = new UserService();

        Pointcut pointcut = new PointcutV1();

        MethodInterceptor methodInterceptor = new MethodInterceptor() {
            @Override
            public Object invoke(MethodInvocation methodInvocation) throws Throwable {
                long l = System.nanoTime();
                Object proceed = methodInvocation.proceed();
                System.out.println("执行耗时：" + (System.nanoTime() - l));
                return proceed;
            }
        };


        //创建Advisor，将pointcut和advice组装起来
        DefaultPointcutAdvisor advisor = new DefaultPointcutAdvisor(pointcut, methodInterceptor);

        //通过spring代理工具创建代理
        ProxyFactory proxyFactory = new ProxyFactory();

        //为工厂指定目标对象
        proxyFactory.setTarget(target);

        //调用addAdi 指定目标对象增强的功能
        proxyFactory.addAdvisor(advisor);

        //创建代理对象
        Object proxy = proxyFactory.getProxy();

        UserService userService = (UserService) proxy;

        System.out.println(userService);
        System.out.println(target);
        System.out.println(target== userService);

        userService.work("石贵武哈哈");

    }
}
